package cn.iocoder.yudao.module.book.controller.app.classes;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.book.controller.app.classes.vo.*;
import cn.iocoder.yudao.module.book.controller.app.lock.vo.AppCheckInEnhancedRespVO;
import cn.iocoder.yudao.module.book.service.WeChat.SchemeService;
import cn.iocoder.yudao.module.book.service.classes.ClassesService;
import cn.iocoder.yudao.module.book.service.members.ClassMembersService;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Tag(name = "用户 App - 班级")
@RestController
@RequestMapping("/api/book/banji")
public class AppClassesController {

    @Resource
    private ClassesService classesService;

    @Resource
    private userDTOService userService;

    @Resource
    private ClassMembersService classMembersService;

    @Resource
    private WxMaService wxMaService;

    @Resource
    private SchemeService schemeService;


    @PostMapping("/create")
    @Operation(summary = "创建班级")
    public CommonResult<Integer> createBanji(@RequestBody AppClassesSaveReqVO createReqVO) {
        createReqVO.setUserId(userService.getCurrentUserId());
        createReqVO.setCname(createReqVO.getCname());
        return CommonResult.success(classesService.InsertClasses(createReqVO));
    }

    @PostMapping("/join")
    @Operation(summary = "加入班级")
    public CommonResult<String> joinBanji(@RequestBody AppClassesRespVO joinReqVO) {
        Long userId = userService.getCurrentUserId();
        String result = classesService.joinClass(joinReqVO.getCommand(), userId);
        return CommonResult.success(result);
    }

    @GetMapping("/detail/{classId}")
    @Operation(summary = "获得班级详情")
    public CommonResult<AppClassDetailRespVO> getBanjiDetail(@PathVariable("classId") Integer classId) {
        Long userId = userService.getCurrentUserId();
        AppClassDetailRespVO detail = classesService.getClassDetail(classId, userId);
        return CommonResult.success(detail);
    }

    @PostMapping("/manage")
    @Operation(summary = "管理班级")
    public CommonResult<String> manageClass(@RequestBody BanjiManageReqVO reqVO) {
        Long currentUserId = userService.getCurrentUserId();
        String result = classesService.manageClass(reqVO, currentUserId);
        return CommonResult.success(result);
    }

    @GetMapping("/{classId}/members")
    @Operation(summary = "获取班级成员列表")
    public CommonResult<List<AppClassMemberRespVO>> getClassMembers(@PathVariable("classId") Integer classId) {
        Long currentUserId = userService.getCurrentUserId();
        List<AppClassMemberRespVO> members = classesService.getClassMembers(classId, currentUserId);
        return CommonResult.success(members);
    }

    @PostMapping("/quit")
    @Operation(summary = "退出班级")
    public CommonResult<String> quitClass(@RequestBody AppClassesRespVO quitReqVO) {
        Long userId = userService.getCurrentUserId();
        String result = classesService.quitClass(quitReqVO.getCommand(), userId);
        return CommonResult.success(result);
    }

    @GetMapping("/my-classes")
    @Operation(summary = "获取我的班级列表")
    public CommonResult<List<AppClassesRespVO>> getMyClasses() {
        Long userId = userService.getCurrentUserId();
        List<AppClassesRespVO> classList = classesService.getMyClasses(userId);
        return CommonResult.success(classList);
    }

    @GetMapping("/check-status")
    @Operation(summary = "检查用户班级状态")
    public CommonResult<Boolean> checkUserClassStatus() {
        Long userId = userService.getCurrentUserId();
        boolean hasClass = classesService.hasUserJoinedAnyClass(userId);
        return CommonResult.success(hasClass);
    }

    @GetMapping("/preview/{command}")
    @Operation(summary = "预览班级信息（根据口令）")
    public CommonResult<AppClassesRespVO> previewClass(@PathVariable("command") Integer command) {
        AppClassesRespVO classInfo = classesService.previewClassByCommand(command);
        return CommonResult.success(classInfo);
    }

    @GetMapping("/getClassList")
    @Operation(summary = "获得班级列表")
    public CommonResult<List<AppClassesRespVO>> getClassList() {
       // 直接使用 getMyClasses 方法，它已经正确处理了软删除逻辑
       List<AppClassesRespVO> classList = classesService.getMyClasses(userService.getCurrentUserId());
       return CommonResult.success(classList);
    }

    @GetMapping("/{classId}/checkins")
    @Operation(summary = "获取班级打卡记录")
    public CommonResult<List<AppCheckInEnhancedRespVO>> getClassCheckins(@PathVariable("classId") Integer classId) {
        Long userId = userService.getCurrentUserId();
        List<AppCheckInEnhancedRespVO> checkins = classesService.getClassCheckinsEnhanced(classId, userId);
        return CommonResult.success(checkins);
    }

    @PostMapping("/invite")
    @Operation(summary = "生成邀请链接")
    public CommonResult<String> inviteMember(@Valid @RequestBody AppClassesSaveReqVO dto) {
        // 1. 生成唯一的邀请码
        Integer inviteCode = classesService.getCommand(dto.getClassesId());

        // 3. 生成小程序路径
        String path = "pages/join/join";
        String query = "inviteCode=" + inviteCode;

        // 4. 获取小程序scheme链接（适用于微信内直接打开）
        String schemeUrl = schemeService.getWxMaScheme(path, query, null);

        // 5. 或者获取小程序URL Scheme（适用于外部浏览器打开）
        // String urlScheme = wxMaService.getWxMaScheme(path, null, null, null);

        if(schemeUrl==null||schemeUrl.isEmpty()){
            return CommonResult.error(CommonResult.error(500, "生成小程序Scheme链接失败"));
        }
        return CommonResult.success(schemeUrl);
    }



}
